//
//  Alarmer+Rx.swift
//  live
//
//  Created by melvyn on 2018/8/23.
//  Copyright © 2018 NEET. All rights reserved.
//

import UIKit
import RxSwift
import Alarmer

extension Reactive where Base: Alarmer {
    static func present<Element>(by parent: UIViewController?, animated: Bool = true, configuration: @escaping (AnyObserver<Element>) throws -> Alarmer) -> Observable<Element> {

        return Observable.create({ [weak parent](observer) -> Disposable in

            var alarmer: Alarmer
            do {
                alarmer = try configuration(observer)
            } catch let error {
                observer.onError(error)
                return Disposables.create()
            }
            
            guard let parent = parent else {
                observer.onCompleted()
                return Disposables.create()
            }
            
            parent.present(alarmer, animated: animated, completion: nil)
            
            return Disposables.create(with: { [weak alarmer] in
                alarmer?.dismiss(animated: animated, completion: nil)
            })
        })
    }
}
